package com.springboot_blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot_blog.dto.UserQueryDTO;
import com.springboot_blog.dto.UserUpdateDTO;
import com.springboot_blog.entity.User;
import com.springboot_blog.enums.ErrorCodeEnum;
import com.springboot_blog.exception.CustomException;
import com.springboot_blog.mapper.UserMapper;
import com.springboot_blog.service.UserService;
import com.springboot_blog.utils.GeneralConverterUtil;
import com.springboot_blog.vo.PageResult;
import com.springboot_blog.vo.UserListVO;
import com.springboot_blog.vo.UserVO;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;


    @Override
    public PageResult<UserListVO> getUserList(UserQueryDTO userQueryDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(userQueryDTO.getUsername()), User::getUsername, userQueryDTO.getUsername())
                .like(StringUtils.hasText(userQueryDTO.getNickname()), User::getNickname, userQueryDTO.getNickname())
                .like(StringUtils.hasText(userQueryDTO.getEmail()), User::getEmail, userQueryDTO.getEmail())
                .eq(userQueryDTO.getRoleId() != null, User::getRoleId, userQueryDTO.getRoleId())
                .eq(userQueryDTO.getStatus() != null, User::getStatus, userQueryDTO.getStatus())
                .eq(User::getDeleted, 0);

        // 排序
        if ("asc".equalsIgnoreCase(userQueryDTO.getOrderDirection())) {
            queryWrapper.orderByAsc(User::getCreatedAt);
        } else {
            queryWrapper.orderByDesc(User::getCreatedAt);
        }

        //分页查询
        IPage<User> page = new Page<>(userQueryDTO.getPageNum(), userQueryDTO.getPageSize());
        IPage<User> userPage = userMapper.selectPage(page, queryWrapper);

        List<UserListVO> userListVOS = GeneralConverterUtil.convertList(userPage.getRecords(), UserListVO.class);

        return new PageResult<>(userListVOS, userPage.getTotal(), userPage.getCurrent(), userPage.getSize());


    }

    @Override
    public UserVO getUserById(Long id) {
        User user = userMapper.selectById(id);

        if (user == null) {
            throw new CustomException(ErrorCodeEnum.USER_NOT_FOUND);
        }

        return GeneralConverterUtil.convert(user, UserVO.class);
    }

    @Override
    public boolean updateUser(Long id, UserUpdateDTO userUpdateDTO) {
        User user = userMapper.selectById(id);

        if (user == null) {
            throw new CustomException(ErrorCodeEnum.USER_NOT_FOUND);
        }

        GeneralConverterUtil.update(user, userUpdateDTO);

        return userMapper.updateById(user) > 0;
    }

    @Override
    @Transactional
    public boolean deleteUser(Long id) {
        User user = userMapper.selectById(id);

        if (user == null) {
            throw new CustomException(ErrorCodeEnum.USER_NOT_FOUND);
        }

        user.setDeleted(1);

        return userMapper.deleteById(user) > 0;
    }

    @Override
    @Transactional
    public boolean batchDeleteUsers(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new CustomException(ErrorCodeEnum.USER_NOT_FOUND);
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(User::getId, ids);
        queryWrapper.eq(User::getDeleted, 0);
        List<User> users = userMapper.selectList(queryWrapper);

        if (users == null || users.isEmpty()) {
            throw new CustomException(ErrorCodeEnum.USER_NOT_FOUND);
        }

        boolean allSuccess = true;
        for (User user : users) {
            boolean success = deleteUser(user.getId());
            if (!success) {
                allSuccess = false;

            }
        }

        return allSuccess;


    }
}
